import React from 'react';
import { connect } from "dva";
import router from "umi/router";
import { Link } from "react-router-dom";
import { Spin, Table, Icon, Divider, Popconfirm } from 'antd';
import queryString from "query-string";
import { getViewPortHeight, openNotificationWithIcon } from '../../../../utils/comm';
import styles from './index.less';

@connect(({ FlowConfigure, loading }) => ({
  flowConfigStore: FlowConfigure,
  loading,
}))
class VersionManage extends React.Component {

  constructor(props) {
    super(props);
    this.getViewPortHeight = getViewPortHeight;
    this.openNotificationWithIcon = openNotificationWithIcon;
    this.state = {
      pageNum: 1,
      pageSize: 6,
    };
    this.columns = [
      {
        title: "版本号",
        align: 'center',
        dataIndex: "version",
        key: "version",
        width: '80px',
      },
      {
        title: "发布时间",
        align: 'center',
        dataIndex: "createTime",
        key: "createTime",
        // width: '80px',
        render: (v) => {
          return (
            <span
              title={v}
            >
              {v || '-'}
            </span>
          );
        },
      },
      {
        title: "流程模型编码",
        align: 'center',
        dataIndex: "flowCode",
        key: "flowCode",
        // width: '60px',
        render: (v) => {
          return (
            <span
              title={v}
            >
              {v || '-'}
            </span>
          );
        },
      },
      {
        title: "流程模型名称",
        align: 'center',
        dataIndex: "flowName",
        key: "flowName",
        // width: '60px',
        render: (v) => {
          return (
            <span
              title={v}
            >
              {v || '-'}
            </span>
          );
        },
      },
      {
        title: "发布状态",
        align: 'center',
        dataIndex: "status",
        key: "status",
        width: '80px',
        render: (text, record) => {
         return this.getStatus(record.status)
        },
      },
      // {
      //   title: "版本说明",
      //   align: 'center',
      //   dataIndex: "desc",
      //   key: "desc",
      //   width: '45px',
      //   render: (v) => {
      //     return (
      //       <span
      //         title={v}
      //       >
      //         {v}
      //       </span>
      //     );
      //   },
      // },
      {
        title: "运行中实例数量",
        align: 'center',
        dataIndex: "numOfRunning",
        key: "numOfRunning",
        // width: '60px',
        render: (v) => {
          return (
            <span
              title={v}
            >
              {v || '-'}
            </span>
          );
        },
      },
      {
        title: "已完成实例数量",
        align: 'center',
        dataIndex: "numOfCompleted",
        key: "numOfCompleted",
        // width: '60px',
        render: (v) => {
          return (
            <span
              title={v}
            >
              {v || '-'}
            </span>
          );
        },
      },
      {
        title: "操作",
        align: 'center',
        width: '160px',
        dataIndex: "opration",
        render: (text, record) => {
          return (
            <div>
              <Link
                to={{
                  pathname: "/flowmanage/flowconfigure/chartview",
                  search: queryString.stringify({
                    modelid: record.modelId,
                  }),
                }}
              >
                查看流程
              </Link>
              {record.status === 'RUNNING' && <Divider type="vertical" />}
              {record.status === 'RUNNING' && (
                <React.Fragment>
                  <Popconfirm
                    placement="left"
                    title={`确定下线流程：${record.flowName}?`}
                    onConfirm={() => {
                      this.handleOffline(record);
                    }}
                    okText="确定"
                    cancelText="取消"
                  >
                    <a
                      onClick={(e) => {
                        e.preventDefault();
                      }}
                    >
                      下线
                    </a>
                  </Popconfirm>
                </React.Fragment>
              )}
              <Divider type="vertical" />
              <a
                onClick={() => {
                this.handleExport(record);
              }}
              >
                导出
              </a>
            </div>
          );
        },
      },
    ]
  }

  componentDidMount() {
    this.initData();
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({ type: "FlowChart/clearData" });
  }

  initData = () => {
    const { location: { query: { modelKey = '' } }, dispatch } = this.props;
    const { pageNum, pageSize } = this.state;
    dispatch({ type: "FlowConfigure/modelDetailList", payload: { searchKey: modelKey, pageNum, pageSize } });
  };

  handlePageChange = ({ current: pageNum, pageSize }) => {
    this.setState({ pageNum, pageSize }, () => {
      this.initData();
    });
  };

  getStatus = (status) => {
    switch (status) {
      case "HISTORY":
        return (
          <span>历史</span>
        );
      case "RUNNING":
        return (
          <span>线上</span>
        );
      case "DESIGN":
        return (
          <span>设计中</span>
        );
      default:
        return '-';
    }
  };

   // 导出
  handleExport = (record = {}) => {
    const { modelId } = record;
    if (!modelId) return;
    const url = `${window.location.origin}/flow-platform/model/download/json?modelId=${modelId}`;
    window.location.href = url;
  }

  // 下线
  handleOffline = (record = {}) => {
    const { modelId } = record;
    if (!modelId) return;
    const { dispatch } = this.props;
    dispatch({
      type: "FlowConfigure/processOffline",
      payload: { modelId },
    }).then(({ success, errMsg }) => {
      if (success === true) {
        this.openNotificationWithIcon("success", "", "下线成功");
        this.initData();
      } else {
        this.openNotificationWithIcon("error", "", errMsg || "下线失败");
      }
    });
  };

  render() {
    const { loading, flowConfigStore } = this.props;
    const { modelDetailList = [], modelTotalCount = 0 } = flowConfigStore;
    const { pageNum, pageSize } = this.state;
    const dataLoading = loading.effects['FlowConfigure/modelDetailList'];
    return (
      <div className={styles.root}>
        <div onClick={() => { router.push('/flowmanage/flowconfigure') }} className={styles.back}>
          <Icon type="left" />
          返回流程模型列表
        </div>
        <div className={styles.title}>版本管理</div>
        <Spin spinning={dataLoading} delay={200}>
          <Table
            dataSource={modelDetailList}
            columns={this.columns}
            rowKey="flowCode"
            bordered
            className={styles.spacing}
            onChange={this.handlePageChange}
            pagination={{
              showQuickJumper: true,
              showSizeChanger: true,
              pageSizeOptions: ["6", "10", "20", "30"],
              current: pageNum,
              pageSize,
              total: modelTotalCount,
            }}
          />
        </Spin>
      </div>
    );
  }
}

export default VersionManage;